package com.youlu.campus.admin.ca.controller;
import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.entity.CaMaterialConfig;
import com.youlu.campus.entity.VO.req.CaMaterialConfigQueryVO;
import com.youlu.campus.service.ca.CaMaterialConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Objects;

@RestController
public class CaMaterialConfigController {
    @Autowired
    private CaMaterialConfigService caMaterialConfigService;

    @PostMapping("/ca/material-config/list")
    public RestResult list(@RequestBody @Valid CaMaterialConfigQueryVO req) {
        String comId = AuthUtils.getComId();
        Page<CaMaterialConfig> users = caMaterialConfigService.list(req);
        if (users == null) {
            PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
            users = PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0L);
        }
        return RestResultBuilder.builder().success().data(users).build();
    }

    @PostMapping("/ca/material-config/create")
    public RestResult create(@RequestBody @Valid CaMaterialConfig req) {
        String comId = AuthUtils.getComId();
        req.setTenantId(comId);
        caMaterialConfigService.create(req);
        return RestResultBuilder.builder().success().build();
    }

    @PostMapping("/ca/material-config/update")
    public RestResult update(@RequestBody @Valid CaMaterialConfig req) {
        String comId = AuthUtils.getComId();
        req.setTenantId(comId);
        boolean re = caMaterialConfigService.update(req);
        if (re) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @GetMapping("/ca/material-config/delete")
    public RestResult delete(@RequestParam("id") String id) {
        String comId = AuthUtils.getComId();
        boolean re = caMaterialConfigService.delete(id);
        if (re) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @GetMapping("/ca/material-config/find-one")
    public RestResult findOne(@RequestParam("id") String id) {
        String comId = AuthUtils.getComId();
        CaMaterialConfig config = caMaterialConfigService.findOne(id);
        if (Objects.nonNull(config)) {
            return RestResultBuilder.builder().success(config).build();
        }
        return RestResultBuilder.builder().failure().build();
    }
}
